package com.yunc.modules.shop.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.base.utils.BaseConstant;
import com.yunc.modules.shop.entity.ShopAddress;
import com.yunc.modules.shop.mapper.ShopAddressMapper;
import com.yunc.modules.shop.service.IShopAddressService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 地址管理
 *
 * @author congcong tao
 * @create 2018/12/23 10:16 PM
 */
@Service("shopAddressService")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShopAddressServiceImpl extends ServiceImpl<ShopAddressMapper, ShopAddress> implements IShopAddressService {

    private final ShopAddressMapper shopAddressMapper;

    @Override
    public ShopAddress getDefault(String memberId) {
        // 查询默认的
        QueryWrapper<ShopAddress> ew = new QueryWrapper<>();
        ew.eq("member_id", memberId);
        ew.eq("type", "1");
        ShopAddress address = this.getOne(ew);
        if (address != null) {
            return address;
        }
        ew = new QueryWrapper<>();
        ew.eq("member_id", memberId);
        ew.orderByAsc("order_num");
        List<ShopAddress> list = this.list(ew);
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional
    public boolean saveAddress(ShopAddress address) {
        if (StringUtils.equals(address.getType(), BaseConstant.ADDRESS_TYPE_DEFAULT)) {
            shopAddressMapper.updateDefaultType(null);
        }
        return this.save(address);
    }

    @Override
    @Transactional
    public boolean updateAddress(ShopAddress address) {
        if (StringUtils.equals(address.getType(), BaseConstant.ADDRESS_TYPE_DEFAULT)) {
            shopAddressMapper.updateDefaultType(address.getId());
        }
        return this.updateById(address);
    }
}
